function isIP(address) {
    return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(address)
}

function isDomain(name) {
    return /localhost/.test(name) || /^((?:(?:(?:\w[.\-+]?)*)\w)+)((?:(?:(?:\w[.\-+]?){0,62})\w)+)\.(\w{2,6})$/.test(name)
}

function isLocalHost(name) {
    return /\w+/.test(name)
}

function isProxy(proxy) {
    return /^SOCKS/.test(proxy)
}

function removeComment(str) {
    return str.replace(/#.+/gm, '')
}

function splitLines(content) {
    return removeComment(content).split('\n').filter(line => line.trim() !== '').map(line => line.trim().split(/\s/)).map(hosts => {
        return hosts.filter(host => {
            return host.trim() !== ''
        })
    })
}

function getHosts(lines) {
    return lines.filter(host =>
        isIP(
            host[0].indexOf(':') > 0
                ? host[0].substr(0, host[0].indexOf(':'))
                : host[0]
        )
    )
}

function getAddress(add) {
    return add.indexOf(':') > -1 ? add : add + ':80'
}

function getProxies(lines) {
    return lines.filter(proxy => isProxy(proxy[0]))
}

function parseRules(content) {
    var lines = splitLines(content)
    var hosts = getHosts(lines)
    var proxies = getProxies(lines)

    const getHostContent = arr => {
        let hosts = arr.slice()
        let address = getAddress(hosts.shift())
        let result = ''

        hosts.forEach(host => {
            result += `\nif(host === "${host}"){\nreturn "PROXY ${address}; SYSTEM";}\n`
        })
        return result
    }
    const getProxyContent = arr => {
        let method = arr.slice()
        let address = method.shift()
        let result = ''

        method.forEach(add => {
            result += `${address} ${add}; `
        })
        return result
    }

    let hostContent = hosts.reduce((sum, value) => (sum += getHostContent(value)), '')
    let proxyContent = proxies.reduce(
        (sum, value) => (sum += getProxyContent(value)),
        ''
    )
    return {hostContent, proxyContent}
}

function setProxy(content) {
    const result = parseRules(content)
    let pacContent =
        `function FindProxyForURL(url, host) {
            ${result.hostContent}
            else {
                return "SYSTEM";
            }
        }`
    console.info(pacContent)
    if (result.hostContent !== '') {
        clearProxy(function () {
            chrome.proxy.settings.set(
                {
                    value: {
                        mode: 'system',
                        pacScript: {
                            data: pacContent
                        }
                    },
                    scope: 'regular'
                },
                function () {
                }
            )
        })
    } else {
        clearProxy()
    }
}

function clearProxy(cb) {
    cb = cb || function () {
    }
    if (typeof chrome.proxy === 'undefined') return false
    chrome.proxy.settings.set({
        value: {mode: 'system'},
        scope: 'regular'
    }, cb)
}
